
import React from 'react'
import ReactDOM from 'react-dom'

import * as UnitAction  from '../../actions/UnitAction';
import { connect }  from 'react-redux';

class UserSettingEdit extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {}
    }
  }

  componentDidMount() {
    this.$unitList = $(ReactDOM.findDOMNode(this.refs.userEditUnitLists));
    this.$expire_date = $(ReactDOM.findDOMNode(this.refs.expire_date))
  }

  componentDidUpdate () {
    var units = this.props.units;
    var self = this;
    if (units && units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        this.$unitList.hide();
      }else if (!this.state.data.unit_desc || this.state.data.unit_desc.trim() == ''){
        this.$unitList.hide();
      }
      else {
        this.$unitList.show();
      }
    }else {
      this.$unitList.hide();
    }
  }

  componentWillReceiveProps(props) {

    var data = props.data;
    var kerry_user = data.kerry_user,
        unit = data.unit
    var activeData = this.state.data;
    activeData.id = data.id;
    activeData.name = kerry_user?kerry_user.name: ""
    activeData.mobile = kerry_user?kerry_user.mobile: ""
    activeData.reg_code = kerry_user?kerry_user.reg_code: ""
    activeData.expire_date = kerry_user?kerry_user.expire_date: ""
    activeData.created_at = kerry_user?kerry_user.created_at: ""
    activeData.sex = kerry_user?kerry_user.sex:""
    activeData.email = kerry_user?kerry_user.email:""
    activeData.identity_no = kerry_user?kerry_user.identity_no:""
    activeData.emergency_contact = kerry_user?kerry_user.emergency_contact:""
    activeData.emergency_mobile = kerry_user?kerry_user.emergency_mobile:""

    if (!this.state.showList) {
      activeData.unit_desc = unit?unit.unit_desc: ""
    }

    var expire_date = "";
    if (kerry_user && kerry_user.expire_date) {
      var date = new Date(this.state.data.expire_date);
      activeData.expire_year = date.getFullYear();
      activeData.expire_month = (date.getMonth() + 1)+"";
      activeData.expire_day = date.getDate();
    }
    else {
      activeData.expire_year = null;
      activeData.expire_month = null;
      activeData.expire_day = null;
    }

    if (activeData.created_at.length > 0) {
      var date = new Date(activeData.created_at);
      activeData.created_at = date.toLocaleString();
    }

    this.setState({
      data: activeData
    })
  }

  onChange(event, key) {
    var value = $(event.target).val();
    if(key == 'mobile'){
      if(value.length > 11){
        value = value.substr(0,11);
      }
    }

    var data = this.state.data;
    data[key] = value;

    this.setState({
      data: data
    })
  }

  onUnitNumberChange(event) {
    var value = $(event.target).val();
    var data = this.state.data;
    data.unit_desc = value;

    this.setState({
      data: data,
      showList: true
    })
    this.props.dispatch(
      UnitAction.loadUnitsAsync({unit_desc: value})
    )
  }

  onUnitNumberClick(event) {
    var value = $(event.target).html();
    var data = this.state.data;
    data.unit_desc = value;
    this.setState({
      data: data,
      showList: false
    })
  }

  onSexSelect(event, selectedSex){
    var data = this.state.data;
    data.sex = selectedSex
    this.setState({
      data: data
    })
  }

  onDataSubmit() {
    var data = this.state.data;

    var allEmtpy = this.checkEmpty(this.state.data.expire_year) && this.checkEmpty(this.state.data.expire_month)
                && this.checkEmpty(this.state.data.expire_day);
    var allNotEmtpy = (!this.checkEmpty(this.state.data.expire_year)) && (!this.checkEmpty(this.state.data.expire_month))
                && (!this.checkEmpty(this.state.data.expire_day))

    function checkPhone(phone) {
    	var phoneRex = /^([0-9-]+)$/;
    	if (phone == "" || phoneRex.test(phone) == false || phone.length <= 7) {
    		return false;
    	}
    	return true;
    }

    if (allEmtpy || allNotEmtpy) {
      if (allNotEmtpy) {
        var expire_date = this.state.data.expire_year + "-" + this.state.data.expire_month + "-"
                          + this.state.data.expire_day + " 00:00:00";
        data.expire_date = new Date(expire_date)
        if (isNaN(data.expire_date.getTime())) {
          alert("请输入正确的日期!")
          return;
        }
      }else {
        data.expire_date = null;
      }

      // if (!checkPhone(data.mobile)) {
      //   alert("请输入正确的电话")
      //   return
      // }

      this.props.onDataUpdate(data)
      this.setState({
        showList: false,
        data: {}
      })
    }else {
      alert("请输入完整日期!")
    }


  }

  pad(n) {
    return n < 10 ? "0"+n : n;
  }

  checkEmpty(text) {
    return !text || text.length == 0
  }

  renderUnitList() {
    var units = this.props.units
    var self = this;
    if (units && units.success) {
      if (units.data.length == 0 || !this.state.showList) {
        return ""
      }else if (!this.state.data.unit_desc || this.state.data.unit_desc.trim() == ''){
        return ""
      }
      else {
        return units.data.map(function(data) {
          return (
            <li className="list-group-item"
                onClick={(event)=>self.onUnitNumberClick(event)}>{data.unit_desc}</li>
          )
        })
      }
    }else {
      return "";
    }
  }

  render() {
    var self = this;

    return (
      <div className="modal fade" id="UserSettingEdit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="User-modal-label">业主详情</h4>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label for="User-name">业主姓名</label>
                <input ref="UserName" type="text" className="form-control"
                        id="User-name" placeholder="业主姓名" value={this.state.data.name}
                        onChange={(event)=>this.onChange(event, "name")} disabled/>
              </div>
              <div className="form-group">
                <label for="User-sex">性别</label>
                <div className="dropdown">
                <button className="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                <span>{this.state.data.sex?this.state.data.sex:"请选择性别"}</span>
                <span className="caret"></span>
                </button>
                <ul className="dropdown-menu" aria-labelledby="dropdownMenu1">
                  <li><a onClick={(event)=>this.onSexSelect(event, '男')}>男</a></li>
                  <li><a onClick={(event)=>this.onSexSelect(event, '女')}>女</a></li>
                  <li><a onClick={(event)=>this.onSexSelect(event, '其他')}>其他</a></li>
                </ul>
                </div>
              </div>
              <div className="form-group">
                <label for="User-identity">护照／身份证号码</label>
                <input ref="UserIdentity" type = "text" className="form-control"
                       id="User-identity" placeholder="护照／身份证号码" value={this.state.data.identity_no}
                       onChange={(event)=>this.onChange(event,"identity_no")} />
              </div>
              <div className="form-group">
                <label for="User-phone">业主联系电话</label>
                <input ref="UserPhone" type="text" className="form-control"
                        id="User-phone" placeholder="业主联系电话" value={this.state.data.mobile}
                        onChange={(event)=>this.onChange(event, "mobile")}/>
              </div>
              <div className="form-group">
                <label for="User-unit">联系地址</label>
                <input ref="UserUnit" type="text" className="form-control"
                        id="User-unit" placeholder="联系地址" value={this.state.data.unit_desc}
                        onChange={(event)=>this.onUnitNumberChange(event)} disabled/>
                <div className="unit-lists" ref="userEditUnitLists">
                  <ul className="list-group">
                    {this.renderUnitList()}
                  </ul>
                </div>
              </div>

              <div className="form-group">
                <label for="User-email">邮箱</label>
                <input ref="UserEmail" type="text" className="form-control"
                        id="User-email" placeholder="邮箱" value={this.state.data.email}
                        onChange={(event)=>this.onChange(event, "email")}/>
              </div>
              <div className="form-group">
                <label for="mergency-contact">指定联系人姓名</label>
                <input ref="emergencyContact" type="text" className="form-control"
                        id="emergency-contact" placeholder="指定联系人姓名" value={this.state.data.emergency_contact}
                        onChange={(event)=>this.onChange(event, "emergency_contact")}/>
              </div>

              <div className="form-group">
                <label for="emergency-mobile">指定联系人联系电话</label>
                <input ref="emergencyMobile" type="text" className="form-control"
                        id="emergency-mobile" placeholder="指定联系人联系电话" value={this.state.data.emergency_mobile}
                        onChange={(event)=>this.onChange(event, "emergency_mobile")}/>
              </div>

              <div className="form-group f-dn">
                <label for="User-phone">账单ID</label>
                <input ref="UserPhone" type="text" className="form-control"
                        id="User-phone" placeholder="账单ID" value={this.state.data.reg_code}
                        onChange={(event)=>this.onChange(event, "reg_code")} disabled />
              </div>
              <div className="form-group f-dn">
                <label for="User-phone">绑定时间</label>

                <input ref="UserBindDate" type="text" className="form-control"
                        id="User-phone" placeholder="绑定时间" value={this.state.data.created_at}
                        onChange={(event)=>this.onChange(event, "created_at")} disabled/>
              </div>
              <div className="form-group f-dn">
                <label for="User-phone">到期时间</label>
                <div className="row">
                  <input ref="PropertyStartTime" type="text" className="col-sm-1"
                          id="Property-phone" placeholder="年" value={self.state.data.expire_year}
                          onChange={(event)=>this.onChange(event, "expire_year")}/>
                  <span className="col-sm-1">年</span>
                  <input ref="PropertyStartTime" type="text" className=" col-sm-1"
                          id="Property-phone" placeholder="月" value={self.state.data.expire_month}
                          onChange={(event)=>this.onChange(event, "expire_month")}/>
                  <span className="col-sm-1">月</span>
                  <input ref="PropertyStartTime" type="text" className=" col-sm-1"
                          id="Property-phone" placeholder="日" value={self.state.data.expire_day}
                          onChange={(event)=>this.onChange(event, "expire_day")}/>
                  <span className="col-sm-1">日</span>
                </div>
              </div>
              <input ref="UserId" value={self.props.data.id} hidden/>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-default" data-dismiss="modal">取消</button>
              <button type="button" className="btn btn-primary"
                      onClick={(event)=> this.onDataSubmit()}>保存</button>
            </div>

          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    units: state.units
  }
}

export default connect(mapStateToProps)(UserSettingEdit)
